package io.renren.modules.sys.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.ShopOrderVOEntity;
import io.renren.modules.sys.entity.UsersEntity;
import io.renren.modules.sys.service.UsersService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.sys.entity.ShopOrderEntity;
import io.renren.modules.sys.service.ShopOrderService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;


/**
 * 订单
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2019-10-25 17:16:55
 */
@RestController
@RequestMapping("sys/shoporder")
public class ShopOrderController {
    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private UsersService usersService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:shoporder:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = shopOrderService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 统计代理商订单
     */
    @RequestMapping("/agentlist")
    @RequiresPermissions("sys:shoporder:agentlist")
    public R agentlist(@RequestParam Map<String, Object> params){
        PageUtils page = shopOrderService.queryAgentPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 统计业务员订单
     */
    @RequestMapping("/salelist")
    @RequiresPermissions("sys:shoporder:salelist")
    public R salelist(@RequestParam Map<String, Object> params){
        PageUtils page = shopOrderService.querySalePage(params);

        return R.ok().put("page", page);
    }

    /**
     * 统计商户订单
     */
    @RequestMapping("/merchantlist")
    @RequiresPermissions("sys:shoporder:merchantlist")
    public R merchantlist(@RequestParam Map<String, Object> params){
        PageUtils page = shopOrderService.queryMerchantPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 首页列表
     */
    @RequestMapping("/orderList")
    public R orderList(@RequestParam Map<String, Object> params){
        List<ShopOrderVOEntity> newList = new ArrayList<>();
        getDayOfWeek(newList);
        return R.ok().put("list", newList);
    }


    private void getDayOfWeek(List<ShopOrderVOEntity> newList) {

        List<ShopOrderVOEntity> list = shopOrderService.getOrderMoney();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        // 今天是一周中的第几天
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK );

        if (c.getFirstDayOfWeek() == Calendar.SUNDAY) {
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        // 计算一周开始的日期
        c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
        String date = "";
        int one = 0;
        for (int i=1;i<=dayOfWeek-1;i++) {
            c.add(Calendar.DAY_OF_MONTH, 1);
            System.out.println(sdf.format(c.getTime()));

            setImgData(newList, list, sdf, c);
        }
    }

    private void setImgData(List<ShopOrderVOEntity> newList, List<ShopOrderVOEntity> list, SimpleDateFormat sdf, Calendar c) {
        int one;
        String date;
        one = sdf.format(c.getTime()).lastIndexOf("-");
        date = sdf.format(c.getTime()).substring((one+1)).replaceAll("^(0+)", "");
        ShopOrderVOEntity entity =new ShopOrderVOEntity();
        double money = 0.0;
        entity.setActualAmount(String.valueOf(money));
        entity.setDayOfWeek(date+"日");
        newList.add(entity);
        for (ShopOrderVOEntity shopOrderEntity : list) {
            if (isSameDateAll(c.getTime(), shopOrderEntity.getAddTime())) {
                money+=Double.valueOf(shopOrderEntity.getActualAmount());
                entity.setActualAmount(String.valueOf(money));
            }
        }
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:shoporder:info")
    public R info(@PathVariable("id") Integer id){
        ShopOrderEntity shopOrder = shopOrderService.getById(id);

        return R.ok().put("shopOrder", shopOrder);
    }

    /**
     * 月订单数
     */
    @RequestMapping("getCounts")
    public R getCounts(){
        List<ShopOrderVOEntity> list = shopOrderService.getOrderMoney();
        Date dt =new Date();
        Integer count = 0;
        for (ShopOrderVOEntity entity : list) {
            if (isSameDate(entity.getAddTime(),dt)) {
                count++;
            }
        }
        return R.ok().put("count", count);
    }

    /**
     * 月订单金额总数
     */
    @RequestMapping("getMoneyTotal")
    public R getMoneyTotal(){
        List<ShopOrderVOEntity> list = shopOrderService.getOrderMoney();
        Date dt =new Date();
        Double moneyTotal = 0.0;
        for (ShopOrderVOEntity entity : list) {
            if (isSameDate(entity.getAddTime(),dt)) {
                moneyTotal+=Double.valueOf(entity.getActualAmount());
            }
        }
        return R.ok().put("moneyTotal", moneyTotal);
    }

    /**
     * 年月
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDate(Date date1, Date date2) {
        try {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);

            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);

            boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
                    .get(Calendar.YEAR);
            boolean isSameMonth = isSameYear
                    && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
//            boolean isSameDate = isSameMonth
//                    && cal1.get(Calendar.DAY_OF_MONTH) == cal2
//                    .get(Calendar.DAY_OF_MONTH);

            if (isSameYear&&isSameMonth) {
                return isSameMonth;
            }
        } catch (Exception e) {
//            log.error("[RatingEngine] error occurred: ERROR ", e);
            e.printStackTrace();
        }
        return false;


    }


    /**
     * 年月日
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDateAll(Date date1, Date date2) {
        try {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);

            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);

            boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
                    .get(Calendar.YEAR);
            boolean isSameMonth = isSameYear
                    && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
            boolean isSameDate = isSameMonth
                    && cal1.get(Calendar.DAY_OF_MONTH) == cal2
                    .get(Calendar.DAY_OF_MONTH);

            if (isSameYear&&isSameMonth&&isSameDate) {
                return isSameMonth;
            }
        } catch (Exception e) {
//            log.error("[RatingEngine] error occurred: ERROR ", e);
            e.printStackTrace();
        }
        return false;


    }
    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:shoporder:save")
    public R save(@RequestBody ShopOrderEntity shopOrder){
        shopOrderService.save(shopOrder);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:shoporder:update")
    public R update(@RequestBody ShopOrderEntity shopOrder){
        ValidatorUtils.validateEntity(shopOrder);
        shopOrderService.updateById(shopOrder);
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    @RequiresPermissions("sys:shoporder:delete")
    public R delete(@PathVariable("id") Integer id){
        shopOrderService.removeById(id);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/modifyStatus")
    public R modifyStatus(@RequestBody ShopOrderEntity shopOrder){
        ShopOrderEntity shopOrderEntity = shopOrderService.getById(shopOrder.getId());
        int status= shopOrder.getOrderStatus();
        if (2==status)  {
            UsersEntity usersEntity= usersService.getById(shopOrderEntity.getUserId());
            if (null != usersEntity) {
                shopOrderEntity.setOrderStatus(status);
                shopOrderService.updateById(shopOrderEntity);

                Double money= Double.valueOf(usersEntity.getBalance())+Double.valueOf(shopOrderEntity.getActualAmount());
                usersEntity.setBalance(String.valueOf(money));
                usersService.save(usersEntity);
            }

        }else {
            shopOrderEntity.setOrderStatus(status);
            shopOrderService.updateById(shopOrderEntity);
        }

        return R.ok();
    }

}
